package com.hp.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hp.bean.Syslog;
import com.hp.service.SyslogService;
import com.hp.util.JsonData;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * 日志记录
 */
@Controller
@RequestMapping("/syslog")
public class SyslogController {
    @Resource
    private SyslogService service;
    @RequestMapping("list")
    @ResponseBody
    public Object list(Syslog syslog,
            @RequestParam(value = "page", defaultValue = "1") Integer page,
                       @RequestParam(value = "limit", defaultValue = "10") Integer limit
    ){
        PageHelper.startPage(page,limit);
        List<Syslog> list = service.selectSyslogList(syslog);
        return JsonData.buildSuccess(new PageInfo<Syslog>(list));
    }

    /**
     * 查询指定信息下载
     */
    @RequestMapping("/selectListExcel")
    public void selectListExcel(Syslog syslog, HttpServletResponse response) throws Exception {
        List<Syslog> list = service.selectSyslogList(syslog);
       Workbook wb = new XSSFWorkbook();//相当于用鼠标创建了一个excel文件
        Sheet sheet = wb.createSheet("sheet1");//对应与excel文件中左下角的sheet页面（标签）
        Row row = sheet.createRow(0);//对应sheet页面中的行数据
        row.createCell(0).setCellValue("ID");
        row.createCell(0).setCellValue("用户id");
        row.createCell(0).setCellValue("IP");
        for (int i = 0; i < list.size(); i++) {
            Row row1 = sheet.createRow(i + 1);
            Syslog syslog1 = list.get(i);
            row1.createCell(0).setCellValue(syslog1.getId());
            row1.createCell(1).setCellValue(syslog1.getUserid());
            row1.createCell(2).setCellValue(syslog1.getIp());
        }
        ServletOutputStream outputStream = response.getOutputStream();
        response.reset();
        response.setHeader("Content-disposition","attachment;filename=日志文件.xls");
        response.setContentType("application/msexcel");
        wb.write(outputStream);
        outputStream.close();
    }


    /**
     * 上传excel并解析
     */
    @RequestMapping("/upload")
    @ResponseBody
    public Object upload(MultipartFile file, HttpServletRequest request) throws IOException, InvalidFormatException {
        //文件上传
        String originalFilename = file.getOriginalFilename();//文件原始名称
        String upload = request.getSession().getServletContext().getRealPath("/upload");//获取文件上传文件夹的路径
        File upfile = new File(upload);//建立链接并判断是否存在，不存在则创建
        if(!upfile.exists()){
            upfile.mkdirs();
        }
        String filename = upload+File.separator+System.currentTimeMillis()+originalFilename;//生成新的文件名称及构成上传路径
        file.transferTo(new File(filename));//上传
        System.out.println(filename);//输出文件路径

        //解析上传文件
        //创建excel表格，直接关联已存在的excel文件
        Workbook wb = new XSSFWorkbook(new File(filename));
        //获取sheet页签
        Sheet sheet1 = wb.getSheet("sheet1");
        //取出页签中所有的行
        for (Row row : sheet1) {
            if (row.getRowNum() == 0) {
                continue;
            }
            Double id = row.getCell(0).getNumericCellValue();
            String userid = row.getCell(1).getStringCellValue();
            String ip = row.getCell(2).getStringCellValue();
            Syslog syslog = new Syslog();
            System.out.println(id);
            syslog.setId(id.intValue());
            syslog.setUserid(userid);
            syslog.setIp(ip);
            System.out.println(syslog);
            service.insertSyslog(syslog);
        }
        return JsonData.buildSuccess("");
}
}